package com.young.financial.service.impl;

import com.young.financial.config.UrlConstants;
import com.young.financial.constants.FinancialPayConfigEnumConstants;
import com.young.financial.service.IntegralPayService;
import com.young.financial.utils.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
public class IntegralPayServiceImpl implements IntegralPayService {
    @Value("${balancePlatform.platfromMarking}")
    private String platfromMarking;
    @Autowired
    private HttpClientUtils httpClientUtils;
    @Autowired
    private AccessTokenUtil accessTokenUtil;
    @Autowired
    private RedisUtils redisUtils;
    public static final Logger logger = LoggerFactory.getLogger(FinancialBalancePayServiceImpl.class);
    @Override
    public Map<String, Object> integralprepay(Map<String, Object> requestMap) {
        //订单号
        String orderNum = requestMap.get("orderNum").toString();
        //会员id
        String customerUuid = requestMap.get("customerUuid").toString();
        //余额支付总金额
        String payMoney = requestMap.get("payMoney").toString();
        //交易描述
        String subject = requestMap.get("subject").toString();
        //交易描述
        String Authorization = requestMap.get("Authorization").toString();
        //获取平台id

        //获取支付通道类型id
        if(StringUtils.isEmpty(customerUuid)
                ||StringUtils.isEmpty(payMoney)||StringUtils.isEmpty(orderNum)
                ||StringUtils.isEmpty(subject)||StringUtils.isEmpty(Authorization)){
        }
        //缓存中获取token
        String accessToken = null;
        Object object = redisUtils.getValue("blanceAccessToken");
        if (null == object) {
            accessToken = accessTokenUtil.getaccessToken();
        } else {
            accessToken = (String) object;
        }
        requestMap.put("tgAccessToken",accessToken);
        requestMap.put("Authorization",Authorization);
        requestMap.put("platfromMarking",platfromMarking);
        requestMap.put("payType", FinancialPayConfigEnumConstants.INTEGRAL_PAY);
        String result = "";
        try {
            result= httpClientUtils.doPost(UrlConstants.INTEGRALPAY_URL,requestMap);
            logger.info("积分预支付信息回执内容:{}",result);
            Map<String, Object> map = JsonUtils.jsonToMap(result);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("IntegralPayServiceImpl----请求金融中心积分支付接口失败 地址:{},错误信息:{}",UrlConstants.INTEGRALPAY_URL,e.getMessage());
        }
        return null;
    }

    @Override
    public Boolean payment(Map<String, Object> requestMap) {
        logger.info("优点积分代付请求金融中心代付参数:{}",JsonUtils.objectToJson(requestMap));
        Boolean agentcyStatus = false;
        //参数校验
        String outTradeNo = requestMap.get("outTradeNo").toString();
        String integralAmount = requestMap.get("integralAmount").toString();
        String bankName = requestMap.get("bankName").toString();
        String subject = requestMap.get("subject").toString();
        String bankCity = requestMap.get("bankCity").toString();
        String bankAccountName = requestMap.get("bankAccountName").toString();
        String bankCardType = requestMap.get("bankCardType").toString();
        String bankAccountType = requestMap.get("bankAccountType").toString();
        String bankAccountNo = requestMap.get("bankAccountNo").toString();
        if (StringUtils.isEmpty(outTradeNo)||StringUtils.isEmpty(integralAmount)
                ||StringUtils.isEmpty(bankName)
                ||StringUtils.isEmpty(subject)||StringUtils.isEmpty(bankAccountNo)
                ||StringUtils.isEmpty(bankCity)||StringUtils.isEmpty(bankAccountName)
                ||StringUtils.isEmpty(bankCardType)||StringUtils.isEmpty(bankAccountType)){
            return false;
        }
        //缓存中获取token
        String accessToken = null;
        Object object = redisUtils.getValue("blanceAccessToken");
        if (null == object) {
            accessToken = accessTokenUtil.getaccessToken();
        } else {
            accessToken = (String) object;
        }
        requestMap.put("payType", FinancialPayConfigEnumConstants.INTEGRAL_PAY);
        requestMap.put("tgAccessToken",accessToken);
        requestMap.put("platfromMarking",platfromMarking);
        String result = "";
        try {
            result= httpClientUtils.doPost(UrlConstants.INTEGRAL_PAYMENT_URL,requestMap);
            logger.info("IntegralPayServiceImpl----请求金融中心积分代付接口成功 地址:{},积分代付请求参数:{}",UrlConstants.INTEGRAL_PAYMENT_URL,result);
            Map<String, Object> resultMap = JsonUtils.jsonToMap(result);
            agentcyStatus = (Boolean) resultMap.get("agentcyStatus");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("IntegralPayServiceImpl----请求金融中心积分代付接口失败 地址:{},错误信息:{}",UrlConstants.WECHAT_BALANCEAGENCY_URL,e.getMessage());
        }
        logger.info("回执优店余额代付结果"+agentcyStatus);
        return agentcyStatus;
    }

    @Override
    public Map<String, Object> integralrefund(Map<String, Object> requestMap) {
        logger.info("IntegralPayServiceImpl -------------接收团购积分退款参数"+JsonUtils.objectToJson(requestMap));
        //用户id
        Object temp = "";
        temp = requestMap.get("customerId");
        String customerUuid = temp!= null? temp.toString():null;
        //支付id
        temp = requestMap.get("payId");
        String payId = temp!= null? temp.toString():null;
        //退款金额
        temp = requestMap.get("backCurrency");
        String backCurrency = temp!= null? temp.toString():null;
        //退款单号
        temp = requestMap.get("prePayNo");
        String prePayNo = temp!= null? temp.toString():null;
        //退款原因
        temp = requestMap.get("refundReason");
        String refundReason = temp!= null? temp.toString():null;
        //获取token
        temp = requestMap.get("Authorization");
        String Authorization = temp!= null? temp.toString():null;
        //校验参数信息是否完整
        if(StringUtils.isEmpty(customerUuid)||StringUtils.isEmpty(backCurrency)
                ||StringUtils.isEmpty(prePayNo)||StringUtils.isEmpty(refundReason)||StringUtils.isEmpty(Authorization)
                ||StringUtils.isEmpty(payId)){
            return ApiResult.paramIsNull();
        }
        //缓存中获取token
        String accessToken = null;
        Object object = redisUtils.getValue("blanceAccessToken");
        if (null == object) {
            accessToken = accessTokenUtil.getaccessToken();
        } else {
            accessToken = (String) object;
        }

        requestMap.put("platfromMarking",platfromMarking);
        requestMap.put("tgAccessToken",accessToken);
        //todo 保存请求参数
        String result = "";
        try {
            result= httpClientUtils.doPost(UrlConstants.INTEGRAL_REFOUND_URL,requestMap);
            logger.info("IntegralPayServiceImpl----请求金融中心积分退款接口成功 地址:{},积分退款返回信息:{}",UrlConstants.INTEGRAL_REFOUND_URL,result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("IntegralPayServiceImpl----请求金融中心积分退款接口失败 地址:{},错误信息:{}",UrlConstants.INTEGRAL_REFOUND_URL,e.getMessage());
        }
        Map<String, Object> map = JsonUtils.jsonToMap(result);
        if(null ==map ||map.size()<0){
            return ApiResult.failure("");
        }
        if(map.get("return_code").toString().equals("0")){
            return ApiResult.success(map);
        }
        return ApiResult.failure();
    }

    @Override
    public Map<String, Object> integralpay(Map<String, Object> requestMap) {
        logger.info("优店请求金融中心积分异步"+JsonUtils.objectToJson(requestMap));
        String result = "";
        //缓存中获取token
        String accessToken = null;
        Object object = redisUtils.getValue("blanceAccessToken");
        if (null == object) {
            accessToken = accessTokenUtil.getaccessToken();
        } else {
            accessToken = (String) object;
        }
        requestMap.put("tgAccessToken",accessToken);
        logger.info("积分中心发送支付信息"+requestMap);
        try {
            result= httpClientUtils.doPost(UrlConstants.INTEGRAL_ASYN_URL,requestMap);
            Map<String, Object> map = JsonUtils.jsonToMap(result);
            logger.info("IntegralPayServiceImpl----请求金融中心积分异步接口成功 地址:{},积分异步请求参数:{}",UrlConstants.INTEGRAL_ASYN_URL,map);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("IntegralPayServiceImpl----请求金融中心积分异步通知接口失败 地址:{},错误信息:{}",UrlConstants.INTEGRAL_ASYN_URL,e.getMessage());
        }
        return null;
    }

    @Override
    public Map<String, Object> intergralpayQuery(Map<String,Object> requestMap) {
        logger.info("预支付积分主动查询参数"+JsonUtils.objectToJson(requestMap));
        String result = "";
        Object temp = "";
        temp = requestMap.get("orderNum");
        String  orderNum = temp != null ? temp.toString():null;
        //temp = requestMap.get("Authorization");
        //String Authorization  = temp != null ? temp.toString():null;
        if (StringUtils.isEmpty(orderNum)){
            return ApiResult.paramIsNull();
        }
        //缓存中获取token
        String accessToken = null;
        Object object = redisUtils.getValue("blanceAccessToken");
        if (null == object) {
            accessToken = accessTokenUtil.getaccessToken();
        } else {
            accessToken = (String) object;
        }
        requestMap.put("tgAccessToken",accessToken);
        logger.info("积分中心主动查询支付信息"+requestMap);
        try {
            result= httpClientUtils.doPost(UrlConstants.INTEGRAL_QUERY_URL,requestMap);
            logger.info("IntegralPayServiceImpl----请求金融中心积分主动查询接口成功 地址:{},积分查询请求参数:{}",UrlConstants.INTEGRAL_QUERY_URL,result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("IntegralPayServiceImpl----请求金融中心积分主动查询接口失败 地址:{},错误信息:{}",UrlConstants.INTEGRAL_QUERY_URL,e.getMessage());
        }
        return JsonUtils.jsonToMap(result);
    }

    @Override
    public Map<String, Object> integralPaymentQuery(Map<String, Object> requestMap) {
        logger.info("优店金融调用金融中心积分代付查询参数 :{}",JsonUtils.objectToJson(requestMap));
        String result = "";
        Object temp = null;
        temp = requestMap.get("out_trade_no");
        String outTradeNo = temp != null ?temp.toString():null;
        temp = requestMap.get("shopdate");
        String shopdate = temp != null ?temp.toString():null;

        if (StringUtils.isEmpty(outTradeNo)||StringUtils.isEmpty(shopdate)){
            return ApiResult.paramIsNull();
        }
        //缓存中获取token
        String accessToken = null;
        Object object = redisUtils.getValue("tgAccessToken");
        if (null == object) {
            accessToken = accessTokenUtil.getaccessToken();
        } else {
            accessToken = (String) object;
        }
        requestMap.put("tgAccessToken",accessToken);
        requestMap.put("payType", FinancialPayConfigEnumConstants.INTEGRAL_PAY);
        requestMap.put("platfromMarking",platfromMarking);
        try {
            result= httpClientUtils.doPost(UrlConstants.INTEGRAL_PAYMENT_QUERY_URL,requestMap);
            logger.info("IntegralPayServiceImpl----请求金融中心积分代付主动查询接口成功 地址:{},余额代付主动查询请求参数:{}",UrlConstants.INTEGRAL_PAYMENT_QUERY_URL,result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("IntegralPayServiceImpl----请求金融中心积分代付主动查询接口失败 地址:{},错误信息:{}",UrlConstants.INTEGRAL_PAYMENT_QUERY_URL,e.getMessage());
        }
        logger.info("IntegralPayServiceImpl---余额代付主动查询结果:{}",JsonUtils.jsonToMap(result));
        return JsonUtils.jsonToMap(result);
    }

}
